<?php
/**
 * Created by PhpStorm.
 * User: freethy
 * Date: 2018-05-11
 * Time: 10:54
 */


use think\Db;
use app\api\controller\Allot;

//获取用户数据权限
function get_power()
{
    $user_id = get_user_id();
    $res = Db::name('s_user_department')->where(['user_id' => $user_id])->select();
    $data = [];
    foreach ($res as $v) {
        $data[] = $v['department_id'];
    }
    return implode(',', $data);
}
// 前台用户登录信息
function get_index_user_info()
{

    $userInfo = SESSION("INDEX_USER_INFO");

    return $userInfo;
}






//获取用户id
function get_user_id()
{
    $user_id = SESSION("MAP_USER");
    $user_id = intval($user_id);
    return $user_id;
}

//获取用户信息
function get_user()
{
    $user_id = get_user_id();
    $user = Db::name("s_user")->where(["id" => $user_id])->find();
    return $user;
}

//获取用户信息
function get_user_staff_id($id)
{
    if (empty($id)) {
        return [];
    }
    $db = Db();
    $user = $db->name("s_user")->alias('a')->join('gs_staff b', 'a.staff_id=b.id')->field('a.id as user_id,a.name as user_name,b.department_id,b.department_name,b.department_leader')->where(["a.staff_id" => $id])->find();
    return $user;
}

//写日志
function wlog($type, $content, $rel = null)
{
    $user = get_user();
    $data = array();
    $data["ip"] = getClientIP();
    $data["create_time"] = get_date_time();
    $data["type"] = $type;
    $data["content"] = $content;
    $data["rel"] = is_array($rel) ? implode(",", $rel) : $rel;
    if (!empty($user)) {
        $data["user_id"] = $user["id"];
        $data["user_name"] = $user["name"];
    }
    Db::name("s_log")->insert($data);
}

//格式化男女
function formatSex($s)
{
    if ($s == "0") {
        return "男";
    } else if ($s == "1") {
        return "女";
    } else {
        return "";
    }
}

//格式化是否是管理员
function formatIsAdmin($s)
{
    if ($s == "0") {
        return "否";
    } else if ($s == "1") {
        return "是";
    } else {
        return "";
    }
}



//导出excel
function export($title, $columns, $data)
{

    $PHPExcel = new PHPExcel();
    $PHPSheet = $PHPExcel->getActiveSheet();
    $PHPSheet->setTitle($title);

    //拼列
    $colIndex = 0;
    foreach ($columns as $colName => $colText) {
        $PHPSheet->setCellValueExplicit(chr($colIndex + 65) . "1", $colText, \PHPExcel_Cell_DataType::TYPE_STRING);
        $colIndex++;
    }

    //拼数据
    for ($i = 0; $i < count($data); $i++) {
        $colIndex = 0;
        foreach ($columns as $colName => $colText) {
            $PHPSheet->setCellValueExplicit(chr($colIndex + 65) . ($i + 2), $data[$i][$colName], \PHPExcel_Cell_DataType::TYPE_STRING);
            $colIndex++;
        }
    }

    //设置样式
    for ($i = 0; $i < $colIndex; $i++) {
        $PHPSheet->getColumnDimension(chr($i + 65))->setWidth(20);
    }

    $PHPSheet->getStyle("A1:" . chr($colIndex - 1 + 65) . "1")->getFill()->getStartColor()->setARGB('99CCFF');
    $PHPSheet->getStyle("A1:" . chr($colIndex - 1 + 65) . "1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
    $PHPSheet->getStyle("A1:" . chr($colIndex - 1 + 65) . (count($data) + 1))->getBorders()->getAllBorders()->getColor()->setRGB('000000');
    $PHPSheet->getStyle("A1:" . chr($colIndex - 1 + 65) . (count($data) + 1))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
    $PHPSheet->getStyle("A1:" . chr($colIndex - 1 + 65) . "1")->applyFromArray(
        array(
            'alignment' => array(
                'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER)
        )
    );

    //输出excel文件
    ob_end_clean();
    header("pragma:public");
    header("Content-type:application/vnd.ms-excel;charset=utf-8;name=$title.xlsx");
    header("Content-Disposition:attachment;filename=$title.xlsx");
    $objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
    $objWriter->save('php://output');

    die();
}



/**
 * 数组输出
 * @param $o
 */
function dump($o)
{
    echo '<div style="text-align:left; border:1px solid #ccc; margin:10px; padding:10px; background:#eee; display:inline-block;">';
    echo '<pre>';
    print_r($o);
    echo '</pre>';
    echo '</div>';
    exit();
}

/*
 * 获取树数据
 * id列
 * pid列
 * title列
 * */
function get_tree_data($data, $id_col, $pid_col, $title_col)
{
    $plist = array();
    $pre = '';
    dg($data, $plist, 0, $pre, $id_col, $pid_col, $title_col);
    return $plist;
}

//职位
function dg($lst, &$plist, $id, $pre, $id_col, $pid_col, $title_col)
{
    for ($i = 0; $i < count($lst); $i++) {
        if ($lst[$i][$pid_col] != $id) {
            continue;
        }
        $lst[$i][$title_col] = $pre . $lst[$i][$title_col];
        $plist[] = $lst[$i];
        dg($lst, $plist, $lst[$i][$id_col], '├ ' . $pre, $id_col, $pid_col, $title_col);
    }
}

/**
 * 格式化树结构的字符
 */
function format_tree($name)
{
    return trim($name, '├ ');
}

function errorMsg($msg = '操作失败,请稍后再试!')
{

    return json(['code'=>1,'msg'=>$msg]);
}

/**
 * use  操作成功提示
 * by   hugh
 * time 2020/12/29 10:19
 */
function success($data = [])
{
    $msg = '操作成功!';
    return json(['code'=>0,'msg'=>$msg,'data'=>$data]);
}

/**
 * use  重复数据提示
 * by   hugh
 * time 2020/12/29 10:19
 */
function duplication()
{
    return json(['code'=>1,'msg'=>'当前数据已存在,请勿重复操作!']);
}

/**
 * use  缺少数据
 * by   hugh
 * time 2020/12/29 10:21
 */
function fieldEmpty($text)
{
    return json(['code'=>1,'msg'=>$text.'不能为空,请检查!']);
}




function token()
{
    return md5(microtime(true));
}

//生成token
function set_token($key)
{
    $token = token();
    $_SESSION[$key] = $token;

    return $token; //用于给页面传值
}

//对比token
function tokenVer($token,$key)
{
    $return = $token === $_SESSION[$key] ? true: false;

    set_token($key);

    return $return;
}

//清除用户登录信息
function clearLoginInfo()
{
    $redis = new \think\cache\driver\Redis();
    $redis->rm(get_user_id());
    session('MAP_USER', null);
    session_destroy();
    return json(['code'=>403,'msg'=>'登陆已过期,请重新登陆']);

}



/**
 * use  手机号码验证
 * by   hugh
 * time 2020/6/15 17:17
 */
function isPhone($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^[1]\d{10}$#', $mobile) ? true : false;
}

//邮箱格式验证
function isMail($mail)
{
    $pattern = '/^\w{3,}@([a-z]{2,7}|[0-9]{3})\.(com|cn)$/';
    return preg_match_all($pattern, $mail, $matches);
}






